package queue;

import java.util.Scanner;

public class CircleArrayQueueDemo {
    public static void main(String[] args) {

        CircleArray queue = new CircleArray(4);
        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;

        while (loop) {
            System.out.println("s(show): 显示队列");
            System.out.println("e(exit): 退出程序");
            System.out.println("a(add): 添加数据到队列");
            System.out.println("g(get): 从队列获取数据");
            System.out.println("h(head): 查看队列第一个元素");
            key = scanner.next().charAt(0);
            switch (key) {
                case 's':
                    queue.showQueue();
                    break;
                case 'e':
                    System.exit(0);
                case 'a':
                    System.out.println("输入一个数");
                    int value = scanner.nextInt();
                    queue.addElement(value);
                    break;
                case 'g':
                    System.out.println(queue.removeElement());
                    break;
                case 'h':
                    System.out.println(queue.showFirstElement());
                    break;
            }
        }
        scanner.close();
    }
}

class CircleArray {

    private int maxSize; // 队列最大长度
    private int front; // 指向队首元素
    private int rear; // 指向队尾元素后一位
    private int[] arr;

    CircleArray(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        front = 0;
        rear = 0;
    }

    // 判断是否满
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    // 判断是否空
    public boolean isEmpty() {
        return rear == front;
    }

    // 添加数据
    public void addElement(int n) {
        if (isFull()) {
            System.out.println("队列满，不能添加数据");
            return;
        }
        arr[rear] = n;
        rear = (rear + 1) % maxSize; // 将rear后移，但考虑到环形的特点，使用这种方法
    }

    // 移出队列
    public int removeElement() {
        if (isEmpty()) {
            throw new RuntimeException("队列空");
        }
        int temp = arr[front];
        front = (front + 1) % maxSize;
        return temp; // 注意不是return arr[front++];
    }

    // 返回当前队列有效数据个数
    public int size() {
        return (rear + maxSize - front) % maxSize;
    }

    // 输出队列
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列空");
            return;
        }
        // 从front开始遍历一定个数的元素，而不直接输出数组
        for (int i = front; i < front + size(); i++) {
            System.out.printf("arr[%d] = %d\n", i % maxSize, arr[i % maxSize]);
        }
    }

    // 显示队首元素
    public int showFirstElement() {
        if (isEmpty()) {
            throw new RuntimeException("队列空");
        }
        return arr[front];
    }

}